<template>
  <div class="device-extensions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备扩展功能</span>
          <div class="header-controls">
            <el-select v-model="selectedDevice" placeholder="选择设备" @change="onDeviceChange">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-button type="primary" @click="refreshDeviceInfo">
              刷新信息
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="extensions-container" v-if="selectedDevice">
        <!-- 时间同步 -->
        <el-card class="extension-card">
          <template #header>
            <span>时间同步</span>
          </template>
          <div class="time-sync-section">
            <div class="current-time-info">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="设备当前时间">
                  {{ deviceTime || '未获取' }}
                </el-descriptions-item>
                <el-descriptions-item label="系统当前时间">
                  {{ systemTime }}
                </el-descriptions-item>
                <el-descriptions-item label="时间差">
                  <el-tag :type="timeDiffType">
                    {{ timeDiff }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="时区">
                  {{ deviceTimezone || '未设置' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="time-sync-controls">
              <el-button @click="fetchDeviceTime">
                获取设备时间
              </el-button>
              <el-button type="primary" @click="syncDeviceTime">
                同步系统时间到设备
              </el-button>
              <el-button @click="showTimezoneDialog">
                设置时区
              </el-button>
            </div>
          </div>
        </el-card>
        
        <!-- 网络配置 -->
        <el-card class="extension-card">
          <template #header>
            <span>网络配置</span>
          </template>
          <div class="network-config-section">
            <el-form :model="networkConfig" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="IP地址">
                    <el-input v-model="networkConfig.ipAddress" />
                  </el-form-item>
                  <el-form-item label="子网掩码">
                    <el-input v-model="networkConfig.subnetMask" />
                  </el-form-item>
                  <el-form-item label="默认网关">
                    <el-input v-model="networkConfig.gateway" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="首选DNS">
                    <el-input v-model="networkConfig.primaryDns" />
                  </el-form-item>
                  <el-form-item label="备用DNS">
                    <el-input v-model="networkConfig.secondaryDns" />
                  </el-form-item>
                  <el-form-item label="DHCP">
                    <el-switch v-model="networkConfig.dhcpEnabled" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <el-button @click="getNetworkConfig">
                  获取当前配置
                </el-button>
                <el-button type="primary" @click="updateNetworkConfig">
                  更新网络配置
                </el-button>
                <el-button @click="testNetworkConnection">
                  测试连接
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        
        <!-- 设备控制 -->
        <el-card class="extension-card">
          <template #header>
            <span>设备控制</span>
          </template>
          <div class="device-control-section">
            <div class="control-buttons">
              <el-button type="warning" @click="rebootDevice">
                <el-icon><Refresh></Refresh></el-icon>
                重启设备
              </el-button>
              <el-button @click="factoryReset">
                <el-icon><Delete></Delete></el-icon>
                恢复出厂设置
              </el-button>
              <el-button @click="exportConfig">
                <el-icon><Download></Download></el-icon>
                导出配置
              </el-button>
              <el-button @click="showImportDialog">
                <el-icon><Upload></Upload></el-icon>
                导入配置
              </el-button>
            </div>
          </div>
        </el-card>
        
        <!-- 设备能力集 -->
        <el-card class="extension-card">
          <template #header>
            <span>设备能力集</span>
          </template>
          <div class="capabilities-section">
            <el-button @click="getDeviceCapabilities" style="margin-bottom: 15px;">
              获取设备能力集
            </el-button>
            <div class="capabilities-tree" v-if="capabilities">
              <el-tree
                :data="capabilitiesTree"
                :props="treeProps"
                default-expand-all
                node-key="id"
              >
                <template #default="{ data }">
                  <span class="capability-node">
                    <span>{{ data.label }}</span>
                    <el-tag v-if="data.supported !== undefined" :type="data.supported ? 'success' : 'danger'" size="small">
                      {{ data.supported ? '支持' : '不支持' }}
                    </el-tag>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </el-card>
        
        <!-- 性能指标 -->
        <el-card class="extension-card">
          <template #header>
            <div class="performance-header">
              <span>性能指标</span>
              <el-switch 
                v-model="performanceMonitorEnabled"
                active-text="实时监控"
                inactive-text="关闭监控"
                @change="togglePerformanceMonitor"
              />
            </div>
          </template>
          <div class="performance-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-statistic title="CPU使用率" :value="performanceData.cpuUsage" suffix="%">
                  <template #prefix>
                    <el-icon><Cpu></Cpu></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="内存使用率" :value="performanceData.memoryUsage" suffix="%">
                  <template #prefix>
                    <el-icon><Monitor></Monitor></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="存储使用率" :value="performanceData.storageUsage" suffix="%">
                  <template #prefix>
                    <el-icon><FolderOpened></FolderOpened></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="网络带宽" :value="performanceData.networkBandwidth" suffix="Mbps">
                  <template #prefix>
                    <el-icon><Connection></Connection></el-icon>
                  </template>
                </el-statistic>
              </el-col>
            </el-row>
            
            <!-- 性能图表 -->
            <div class="performance-charts" v-if="performanceMonitorEnabled">
              <div class="chart-container">
                <div ref="cpuChartRef" class="chart"></div>
              </div>
              <div class="chart-container">
                <div ref="memoryChartRef" class="chart"></div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <div class="no-device-selected" v-else>
        <el-empty description="请选择设备以查看扩展功能" />
      </div>
    </el-card>
    
    <!-- 时区设置对话框 -->
    <el-dialog v-model="timezoneDialogVisible" title="设置时区" width="400px">
      <el-form :model="timezoneForm">
        <el-form-item label="时区">
          <el-select v-model="timezoneForm.timezone" placeholder="选择时区">
            <el-option 
              v-for="tz in timezones" 
              :key="tz.value"
              :label="tz.label"
              :value="tz.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="timezoneDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setDeviceTimezone">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 配置导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入配置" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleConfigFileChange"
        :limit="1"
        accept=".xml,.json"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled></UploadFilled></el-icon>
        <div class="el-upload__text">
          将配置文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 XML 和 JSON 格式的配置文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="importConfig">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, Delete, Download, Upload, UploadFilled,
  Cpu, Monitor, FolderOpened, Connection
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  syncDeviceTime as apiSyncDeviceTime,
  getDeviceNetworkConfig as apiGetNetworkConfig,
  updateDeviceNetworkConfig as apiUpdateNetworkConfig,
  rebootDevice as apiRebootDevice,
  getDeviceCapabilities as apiGetDeviceCapabilities,
  getDeviceMetrics as getPerformanceMetrics,
} from '@/api/device'
import {
  getDeviceTime,
  exportDeviceConfig,
  importDeviceConfig
} from '@/api/deviceExtensions'
import { getDevices } from '@/api/device'

const selectedDevice = ref('')
const deviceTime = ref('')
const systemTime = ref('')
const deviceTimezone = ref('')
const timezoneDialogVisible = ref(false)
const importDialogVisible = ref(false)
const performanceMonitorEnabled = ref(false)
const capabilities = ref(null)
const uploadRef = ref(null)
const cpuChartRef = ref(null)
const memoryChartRef = ref(null)

const devices = ref([])
const configFile = ref(null)

const networkConfig = reactive({
  ipAddress: '',
  subnetMask: '',
  gateway: '',
  primaryDns: '',
  secondaryDns: '',
  dhcpEnabled: false
})

const timezoneForm = reactive({
  timezone: ''
})

const performanceData = reactive({
  cpuUsage: 0,
  memoryUsage: 0,
  storageUsage: 0,
  networkBandwidth: 0
})

const timezones = ref([
  { label: 'UTC+8 (北京时间)', value: 'Asia/Shanghai' },
  { label: 'UTC+0 (格林威治时间)', value: 'UTC' },
  { label: 'UTC-5 (美国东部时间)', value: 'America/New_York' },
  { label: 'UTC-8 (美国太平洋时间)', value: 'America/Los_Angeles' },
  { label: 'UTC+1 (中欧时间)', value: 'Europe/Berlin' },
  { label: 'UTC+9 (日本时间)', value: 'Asia/Tokyo' }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

let performanceTimer = null
let cpuChart = null
let memoryChart = null
let cpuData = []
let memoryData = []
let timeLabels = []

// 计算属性
const timeDiff = computed(() => {
  if (!deviceTime.value || !systemTime.value) return '未知'
  
  const deviceTimestamp = new Date(deviceTime.value).getTime()
  const systemTimestamp = new Date(systemTime.value).getTime()
  const diff = Math.abs(deviceTimestamp - systemTimestamp) / 1000
  
  if (diff < 60) {
    return `${Math.round(diff)}秒`
  } else if (diff < 3600) {
    return `${Math.round(diff / 60)}分钟`
  } else {
    return `${Math.round(diff / 3600)}小时`
  }
})

const timeDiffType = computed(() => {
  if (!deviceTime.value || !systemTime.value) return 'info'
  
  const deviceTimestamp = new Date(deviceTime.value).getTime()
  const systemTimestamp = new Date(systemTime.value).getTime()
  const diff = Math.abs(deviceTimestamp - systemTimestamp) / 1000
  
  if (diff < 30) return 'success'
  if (diff < 300) return 'warning'
  return 'danger'
})

const capabilitiesTree = computed(() => {
  if (!capabilities.value) return []
  
  return [
    {
      id: 'media',
      label: '媒体服务',
      children: [
        { id: 'streaming', label: '流媒体', supported: capabilities.value.media?.streaming },
        { id: 'recording', label: '录像', supported: capabilities.value.media?.recording },
        { id: 'snapshot', label: '抓拍', supported: capabilities.value.media?.snapshot }
      ]
    },
    {
      id: 'ptz',
      label: 'PTZ控制',
      children: [
        { id: 'absolute', label: '绝对定位', supported: capabilities.value.ptz?.absolute },
        { id: 'relative', label: '相对定位', supported: capabilities.value.ptz?.relative },
        { id: 'continuous', label: '连续移动', supported: capabilities.value.ptz?.continuous },
        { id: 'presets', label: '预设位', supported: capabilities.value.ptz?.presets }
      ]
    },
    {
      id: 'events',
      label: '事件服务',
      children: [
        { id: 'basic', label: '基础事件', supported: capabilities.value.events?.basic },
        { id: 'pullpoint', label: '拉取点', supported: capabilities.value.events?.pullpoint },
        { id: 'notification', label: '通知', supported: capabilities.value.events?.notification }
      ]
    },
    {
      id: 'analytics',
      label: '分析服务',
      children: [
        { id: 'motion', label: '运动检测', supported: capabilities.value.analytics?.motion },
        { id: 'tampering', label: '篡改检测', supported: capabilities.value.analytics?.tampering },
        { id: 'line_crossing', label: '越线检测', supported: capabilities.value.analytics?.lineCrossing }
      ]
    }
  ]
})

// 更新系统时间
const updateSystemTime = () => {
  systemTime.value = new Date().toLocaleString()
}

// 加载设备列表
const loadDevices = async () => {
  try {
    const response = await getDevices()
    devices.value = response.data.content || []
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

// 设备变化处理
const onDeviceChange = () => {
  if (selectedDevice.value) {
    refreshDeviceInfo()
  }
}

// 刷新设备信息
const refreshDeviceInfo = () => {
  fetchDeviceTime()
  getNetworkConfig()
  getPerformanceData()
}

// 获取设备时间
const fetchDeviceTime = async () => {
  if (!selectedDevice.value) return
  
  try {
    const response = await getDeviceTime(selectedDevice.value)
    deviceTime.value = response.data.currentTime
    deviceTimezone.value = response.data.timezone
  } catch (error) {
    ElMessage.error('获取设备时间失败')
  }
}

// 同步设备时间
const syncDeviceTime = async () => {
  try {
    await apiSyncDeviceTime(selectedDevice.value)
    ElMessage.success('时间同步成功')
    await fetchDeviceTime()
  } catch (error) {
    ElMessage.error('时间同步失败')
  }
}

// 显示时区设置对话框
const showTimezoneDialog = () => {
  timezoneForm.timezone = deviceTimezone.value
  timezoneDialogVisible.value = true
}

// 设置设备时区
const setDeviceTimezone = async () => {
  try {
    // TODO: 实现时区设置API
    // await apiSetDeviceTimezone(selectedDevice.value, timezoneForm.timezone)
    ElMessage.warning('时区设置功能暂未实现')
    timezoneDialogVisible.value = false
    // await fetchDeviceTime()
  } catch (error) {
    ElMessage.error('时区设置失败')
  }
}

// 获取网络配置
const getNetworkConfig = async () => {
  if (!selectedDevice.value) return
  
  try {
    const response = await apiGetNetworkConfig(selectedDevice.value)
    Object.assign(networkConfig, response.data)
  } catch (error) {
    ElMessage.error('获取网络配置失败')
  }
}

// 更新网络配置
const updateNetworkConfig = async () => {
  try {
    await apiUpdateNetworkConfig(selectedDevice.value, networkConfig)
    ElMessage.success('网络配置更新成功')
  } catch (error) {
    ElMessage.error('网络配置更新失败')
  }
}

// 测试网络连接
const testNetworkConnection = async () => {
  try {
    // TODO: 实现网络连接测试
    ElMessage.success('网络连接正常')
  } catch (error) {
    ElMessage.error('网络连接测试失败')
  }
}

// 重启设备
const rebootDevice = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重启设备吗？重启过程中设备将暂时不可用。',
      '确认重启',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiRebootDevice(selectedDevice.value)
    ElMessage.success('设备重启命令已发送')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设备重启失败')
    }
  }
}

// 恢复出厂设置
const factoryReset = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要恢复出厂设置吗？此操作将清除所有配置，无法撤销！',
      '确认恢复出厂设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // TODO: 实现恢复出厂设置
    ElMessage.success('恢复出厂设置命令已发送')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复出厂设置失败')
    }
  }
}

// 导出配置
const exportConfig = async () => {
  try {
    const response = await exportDeviceConfig(selectedDevice.value)
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/xml' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `device_config_${selectedDevice.value}.xml`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('配置导出成功')
  } catch (error) {
    ElMessage.error('配置导出失败')
  }
}

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
}

// 处理配置文件变化
const handleConfigFileChange = (file) => {
  configFile.value = file.raw
}

// 导入配置
const importConfig = async () => {
  if (!configFile.value) {
    ElMessage.warning('请选择配置文件')
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', configFile.value)
    
    await importDeviceConfig(selectedDevice.value, formData)
    ElMessage.success('配置导入成功')
    importDialogVisible.value = false
    configFile.value = null
    uploadRef.value?.clearFiles()
  } catch (error) {
    ElMessage.error('配置导入失败')
  }
}

// 获取设备能力集
const getDeviceCapabilities = async () => {
  try {
    const response = await apiGetDeviceCapabilities(selectedDevice.value)
    capabilities.value = response.data
    ElMessage.success('设备能力集获取成功')
  } catch (error) {
    ElMessage.error('获取设备能力集失败')
  }
}

// 获取性能数据
const getPerformanceData = async () => {
  if (!selectedDevice.value) return
  
  try {
    const response = await getPerformanceMetrics(selectedDevice.value)
    Object.assign(performanceData, response.data)
    
    // 更新图表数据
    if (performanceMonitorEnabled.value) {
      updateChartData()
    }
  } catch (error) {
    console.error('获取性能数据失败:', error)
  }
}

// 切换性能监控
const togglePerformanceMonitor = (enabled) => {
  if (enabled) {
    startPerformanceMonitor()
    nextTick(() => {
      initCharts()
    })
  } else {
    stopPerformanceMonitor()
  }
}

// 开始性能监控
const startPerformanceMonitor = () => {
  performanceTimer = setInterval(() => {
    getPerformanceData()
  }, 5000)
}

// 停止性能监控
const stopPerformanceMonitor = () => {
  if (performanceTimer) {
    clearInterval(performanceTimer)
    performanceTimer = null
  }
}

// 初始化图表
const initCharts = () => {
  if (cpuChartRef.value) {
    cpuChart = echarts.init(cpuChartRef.value)
    cpuChart.setOption({
      title: { text: 'CPU使用率', left: 'center' },
      xAxis: { type: 'category', data: timeLabels },
      yAxis: { type: 'value', max: 100, min: 0 },
      series: [{
        data: cpuData,
        type: 'line',
        smooth: true,
        areaStyle: {}
      }]
    })
  }
  
  if (memoryChartRef.value) {
    memoryChart = echarts.init(memoryChartRef.value)
    memoryChart.setOption({
      title: { text: '内存使用率', left: 'center' },
      xAxis: { type: 'category', data: timeLabels },
      yAxis: { type: 'value', max: 100, min: 0 },
      series: [{
        data: memoryData,
        type: 'line',
        smooth: true,
        areaStyle: {}
      }]
    })
  }
}

// 更新图表数据
const updateChartData = () => {
  const now = new Date().toLocaleTimeString()
  
  timeLabels.push(now)
  cpuData.push(performanceData.cpuUsage)
  memoryData.push(performanceData.memoryUsage)
  
  // 保持最新的20个数据点
  if (timeLabels.length > 20) {
    timeLabels.shift()
    cpuData.shift()
    memoryData.shift()
  }
  
  // 更新图表
  if (cpuChart) {
    cpuChart.setOption({
      xAxis: { data: timeLabels },
      series: [{ data: cpuData }]
    })
  }
  
  if (memoryChart) {
    memoryChart.setOption({
      xAxis: { data: timeLabels },
      series: [{ data: memoryData }]
    })
  }
}

onMounted(() => {
  loadDevices()
  updateSystemTime()
  
  // 每秒更新系统时间
  setInterval(updateSystemTime, 1000)
})

onUnmounted(() => {
  stopPerformanceMonitor()
  if (cpuChart) {
    cpuChart.dispose()
  }
  if (memoryChart) {
    memoryChart.dispose()
  }
})
</script>

<style scoped>
.device-extensions {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.extensions-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.extension-card {
  background: #f8f9fa;
}

.time-sync-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.time-sync-controls {
  display: flex;
  gap: 10px;
}

.network-config-section {
  padding: 10px 0;
}

.device-control-section {
  padding: 10px 0;
}

.control-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.capabilities-section {
  padding: 10px 0;
}

.capabilities-tree {
  margin-top: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.capability-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.performance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.performance-section {
  padding: 10px 0;
}

.performance-charts {
  margin-top: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.chart {
  width: 100%;
  height: 300px;
}

.no-device-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>